package com.intramirror.product.algorithm.impl;

import com.intramirror.product.algorithm.IAggregateAlgorithm;
import com.intramirror.product.entity.PatternFromOne;
import com.intramirror.product.entity.Product;
import com.intramirror.product.entity.Spu;
import com.intramirror.product.exception.BusinessException;
import com.intramirror.utils.transform.JsonTransformUtil;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * Created on 2018/1/30.
 * @author 123
 */
@Service("matchFromOne")
public class MatchFromOne extends BaseAggregateAlgorithm implements IAggregateAlgorithm {
    private static final Logger LOGGER = LoggerFactory.getLogger(MatchFromTwo.class);

    @Override
    public Spu aggregateWithPattern(Product product, String pattern) throws BusinessException {
        PatternFromOne entity = JsonTransformUtil.readValue(pattern, PatternFromOne.class);

        String designerId = product.getDesignerId();

        if (entity.getRtrim_color_code() != null && entity.getRtrim_color_code()) {
            int index = designerId.lastIndexOf(product.getColorCode());
            if (index + product.getColorCode().length() == designerId.length()) {
                designerId = designerId.substring(0, index);
            } else {
                LOGGER.info("Not find color code in designerId.");
            }
        }

        if (entity.getPre_replace() != null) {
            designerId = replaceWithPattern(product.getDesignerId(), entity.getPre_replace(), entity.getPre_replace_to());
        }

        product.setDesignerId(designerId);
        Spu matchedSpu = exactMatchWithExistsSpu(product);
        if (matchedSpu != null) {
            return matchedSpu;
        }

        inexactMatchWithExistsSpu(product);

        Spu spu = new Spu();
        Pattern r = Pattern.compile(entity.getPattern());
        Matcher m = r.matcher(designerId);
        try {
            if (m.find()) {
                LOGGER.debug("Already get designerId {} and colorCode {} with pattern {}.", m.group(1), m.group(2), pattern);
                spu.setDesignerId(m.group(1));
                spu.setColorCode(m.group(2));
            } else {
                LOGGER.debug("Could not match designerId and colorCode.");
                throw new BusinessException("Could not match designerId and colorCode.");
            }
        } catch (Exception e) {
            throw new BusinessException("Get designerId and colorCode failed.", e);
        }
        return spu;
    }

}
